package com.ycsj.goldmedalnewconcept.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.flyco.animation.BaseAnimatorSet;
import com.flyco.dialog.listener.OnBtnLeftClickL;
import com.flyco.dialog.listener.OnBtnRightClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.google.gson.Gson;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.squareup.timessquare.CalendarView;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.bean.NoteNotify;
import com.ycsj.goldmedalnewconcept.bean.TipsResq;
import com.ycsj.goldmedalnewconcept.bean.TipsResq.TipsResqListDetail;
import com.ycsj.goldmedalnewconcept.constant.Constant;
import com.ycsj.goldmedalnewconcept.utils.SPUtil;
import com.ycsj.goldmedalnewconcept.utils.UiHelper;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

//import com.squareup.timessquare.CalendarPickerView;

//备忘录
public class TipsActivity extends Activity {
	private CalendarView bc_calendar;
	private ImageView note_tips;
	private ListView lv_tips;
	private Date currclickdate = new Date();
	private Boolean isDateSelected = false;
	public static List<NoteNotify> mNotifyList = new ArrayList<NoteNotify>();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_tips);
		initView();
		setOnListener();
	}

	@Override
	protected void onResume() {
		super.onResume();
		noteDetailList.removeAll(noteDetailList);
		initData(currclickdate);

	}

	private void initData(Date date) {

		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM");
		String ym = dateFormat.format(date);

		OkHttpClient mOkHttpClient = new OkHttpClient();
		FormEncodingBuilder builder = new FormEncodingBuilder();
		builder.add("type", "2");
		builder.add("c", SPUtil.getString(TipsActivity.this, "account", ""));
		builder.add("role", SPUtil.getString(TipsActivity.this, "role", ""));
		builder.add("ym", ym);
		Log.e("test", "ym-" + ym);
		Request request = new Request.Builder()
				.url(Constant.SERVER_URL + "PersonalAssistantMsg")
				.post(builder.build()).build();
		mOkHttpClient.newCall(request).enqueue(callBack);
	}

	private void setOnListener() {

		note_tips.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (!markList.contains(new Date().getDate())) {

					SimpleDateFormat dateFormat = new SimpleDateFormat(
							"yyyy-MM-dd");
					String date = dateFormat.format(new Date());
					Intent intent = new Intent(TipsActivity.this,
							NoteActivity.class);
					intent.putExtra("date", date);
					startActivity(intent);
				} else {
					NormalDialogCustomAttr();
				}
			}
		});

		bc_calendar.setOnMonthChangedListener(new CalendarView.OnMonthChangedListener() {

			@Override
			public void onChangedToPreMonth(Date dateOfMonth) {
				currclickdate = dateOfMonth;
				markList.removeAll(markList);
				noteDetailList.removeAll(noteDetailList);
				initData(dateOfMonth);
			}

			@Override
			public void onChangedToNextMonth(Date dateOfMonth) {
				final int month = dateOfMonth.getMonth();
				Log.e("testtips", "" + month);
				currclickdate = dateOfMonth;
				markList.removeAll(markList);
				noteDetailList.removeAll(noteDetailList);
				initData(dateOfMonth);
			}
		});
		bc_calendar.setOnDateSelectedListener(new CalendarView.OnDateSelectedListener() {

			@Override
			public void onDateUnselected(Date date) {

			}

			@Override
			public void onDateSelected(final Date date) {
				currclickdate = date;
				isDateSelected = true;
				if (isDateSelected) {

					note_tips.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							Date nowdate = new Date();// 取时间
							Calendar calendar = new GregorianCalendar();
							calendar.setTime(date);
							calendar.add(calendar.DATE, -1);// 把日期往后增加一天.整数往后推,负数往前移动
							nowdate = calendar.getTime();

							int i = currclickdate.compareTo(nowdate);
							Log.e("test", "i=" + i);
							if (!markList.contains(date.getDate())) {

								SimpleDateFormat dateFormat = new SimpleDateFormat(
										"yyyy-MM-dd");
								String date = dateFormat.format(currclickdate);
								Intent intent = new Intent(TipsActivity.this,
										NoteActivity.class);
								intent.putExtra("date", date);
								startActivity(intent);
							} else {
								NormalDialogCustomAttr();
							}
						}
					});
				} else {
					Toast.makeText(TipsActivity.this, "请选择日期", Toast.LENGTH_SHORT).show();
				}

			}
		});
	}

	private void initView() {
		bc_calendar =  findViewById(R.id.bc_calendar);
		lv_tips = (ListView) findViewById(R.id.lv_tips);
		note_tips = (ImageView) findViewById(R.id.note_tips);
	}

	class MyAdapter extends BaseAdapter {
		ArrayList<TipsResqListDetail> list;

		public MyAdapter(ArrayList<TipsResqListDetail> noteDetailList) {
			list = noteDetailList;
		}

		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			ViewHolder vh = null;
			if (convertView == null) {
				vh = new ViewHolder();
				convertView = View.inflate(parent.getContext(),
						R.layout.item_date, null);
				vh.tv_content = (TextView) convertView
						.findViewById(R.id.tv_note_content);
				vh.tv_title = (TextView) convertView
						.findViewById(R.id.tv_note_tag);
				vh.tv_date = (TextView) convertView
						.findViewById(R.id.tv_notice_date);
				vh.iv_note_delete = (ImageView) convertView
						.findViewById(R.id.iv_note_delete);
				convertView.setTag(vh);

			} else {
				vh = (ViewHolder) convertView.getTag();
			}
			vh.tv_content.setText(list.get(position).content);
			vh.tv_title.setText(list.get(position).tag);
			vh.tv_date.setText(list.get(position).begin_date);
			vh.iv_note_delete.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					OkHttpClient mOkHttpClient = new OkHttpClient();
					FormEncodingBuilder builder = new FormEncodingBuilder();
					builder.add("type", "3");
					builder.add("c",
							SPUtil.getString(TipsActivity.this, "account", ""));
					builder.add("role",
							SPUtil.getString(TipsActivity.this, "role", ""));
					builder.add("ymd", list.get(position).begin_date);
					builder.add("status", "-1");
					Request request = new Request.Builder()
							.url(Constant.SERVER_URL + "PersonalAssistantMsg")
							.post(builder.build()).build();
//					mOkHttpClient.newCall(request).enqueue(callBack2);
					
//					try {
//						markList.remove(position);
//						noteDetailList.remove(fromJson.list.get(position));
//					} catch (Exception e) {
//						// TODO: handle exception
//					}
					UiHelper.showDialog(TipsActivity.this, "删除中...");

					mOkHttpClient.newCall(request).enqueue(new Callback() {

						@Override
						public void onResponse(Response arg0)
								throws IOException {

							try {
								for (int i = 0; i < mNotifyList.size(); i++) {
									if(list.get(position).begin_date.equals(mNotifyList.get(i).date)){
										mNotifyList.get(i).am.cancel(mNotifyList.get(i).sender);
									}
								}
							} catch (Exception e) {
								// TODO: handle exception
							}
							
							// 请求成功
							runOnUiThread(new Runnable() {
								public void run() {

									UiHelper.dismissDialog();

									// 执行删除的操作;
									markList.remove(position);
									noteDetailList.remove(position);
									
									myAdapter.notifyDataSetChanged();
									int size = markList.size();
									final Integer[] array = (Integer[]) markList
											.toArray(new Integer[size]);

									bc_calendar.markDatesOfMonth(
											(currclickdate.getYear() + 1900),
											currclickdate.getMonth(), true,
											false, false, array);
								}
							});

						}

						@Override
						public void onFailure(Request arg0, IOException arg1) {
							runOnUiThread(new Runnable() {
								public void run() {
									UiHelper.dismissDialog();
									Toast.makeText(TipsActivity.this,
											"网络异常,删除失败", Toast.LENGTH_LONG)
											.show();
								}
							});
						}
					});
				}
			});
			return convertView;
		}

		class ViewHolder {
			private TextView tv_title;
			private TextView tv_date;
			private TextView tv_content;
			private ImageView iv_note_delete;
		}
	}

	ArrayList<Integer> markList = new ArrayList<Integer>();
	ArrayList<Integer> noteList = new ArrayList<Integer>();
	ArrayList<TipsResqListDetail> noteDetailList = new ArrayList<TipsResqListDetail>();
	private MyAdapter myAdapter = new MyAdapter(noteDetailList);
	Handler handler = new Handler();
	private TipsResq fromJson;
	Callback callBack = new Callback() {

		@Override
		public void onResponse(Response arg0) throws IOException {
			String json = arg0.body().string();
			Gson gson = new Gson();
			noteDetailList.removeAll(noteDetailList);
			markList.removeAll(markList);
			fromJson = gson.fromJson(json, TipsResq.class);
			if (!("{\"state\":\"-1\"}").equals(json)) {
				if (!fromJson.list.isEmpty()) {

					for (int i = 0; i < fromJson.list.size(); i++) {
						String[] splits = fromJson.list.get(i).begin_date
								.split("-");
						int a = Integer.parseInt(splits[1]);
						int b = Integer.parseInt(splits[2]);
						if (a == (currclickdate.getMonth() + 1)) {
							markList.add(b);
						}
						noteDetailList.add(fromJson.list.get(i));
					}
					
//					for (int j = 0; j < noteDetailList.size(); j++) {
//						Log.e("TEST", "notifydate"+noteDetailList.get(j).notice_date);
//					}
					int size = markList.size();
					final Integer[] array = (Integer[]) markList
							.toArray(new Integer[size]);
					handler.postDelayed(new Runnable() {

						@Override
						public void run() {

							bc_calendar.markDatesOfMonth(
									(currclickdate.getYear() + 1900),
									currclickdate.getMonth(), true, false,
									false, array);

							lv_tips.setAdapter(myAdapter);
						}
					}, 100);
				}
			}
		}

		@Override
		public void onFailure(Request arg0, IOException arg1) {

		}
	};

	Callback callBack2 = new Callback() {

		@Override
		public void onResponse(Response arg0) throws IOException {
			handler.postDelayed(new Runnable() {

				@Override
				public void run() {

					myAdapter.notifyDataSetChanged();
					int size = markList.size();
					final Integer[] array = (Integer[]) markList
							.toArray(new Integer[size]);

					bc_calendar.markDatesOfMonth(
							(currclickdate.getYear() + 1900),
							currclickdate.getMonth(), true, false, false, array);

				}
			}, 0);
		}

		@Override
		public void onFailure(Request arg0, IOException arg1) {

		}
	};

	private BaseAnimatorSet bas_in;
	private BaseAnimatorSet bas_out;

	private String title;
	private String content;
	private String notifydate;

	public void setBasIn(BaseAnimatorSet bas_in) {
		this.bas_in = bas_in;
	}

	public void setBasOut(BaseAnimatorSet bas_out) {
		this.bas_out = bas_out;
	}

	private void NormalDialogCustomAttr() {

		final NormalDialog dialog = new NormalDialog(this);
		dialog.content("当天已有备忘录")//
				.style(NormalDialog.STYLE_TWO)//
				.titleTextSize(23)//
				.showAnim(bas_in)//
				.dismissAnim(bas_out)//
				.show();
		dialog.setCanceledOnTouchOutside(false);
		dialog.btnText("取消", "修改");
		dialog.setOnBtnLeftClickL(new OnBtnLeftClickL() {

			@Override
			public void onBtnLeftClick() {

				dialog.dismiss();
			}
		});
		
		dialog.setOnBtnRightClickL(new OnBtnRightClickL() {

		

			@Override
			public void onBtnRightClick() {
				SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
				String date = dateFormat.format(currclickdate);

				// 遍历集合中的值
				for (int i = 0; i < noteDetailList.size(); i++) {

					if (date.equals(noteDetailList.get(i).begin_date)) {

						// 证明当前备忘录中已经编写了备忘录
						title = noteDetailList.get(i).tag;
						content = noteDetailList.get(i).content;
						
						break;
					}
				}

				Intent intent = new Intent(TipsActivity.this,
						NoteActivity.class);
				
				intent.putExtra("date", date);
				intent.putExtra("title", title);
				intent.putExtra("content", content);
				for (int j = 0; j < mNotifyList.size(); j++) {
					if(mNotifyList.get(j).date.equals(date)){
						notifydate = mNotifyList.get(j).notify;
					}
				}
				
				
				
				intent.putExtra("notifydate", notifydate);
				Log.e("TEST", "notifydate"+notifydate);
				startActivity(intent);
				dialog.dismiss();
			}
		});
	}
}






